import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useUser = defineStore('user',()=>{
  const address = ref(JSON.parse(uni.getStorageSync('address') || '{}'))
  const token = ref(uni.getStorageSync('token') || '')
  // 用户的信息对象
  const userinfo = ref(JSON.parse(uni.getStorageSync('userinfo') || '{}'))
  const updateUserInfo = (userInfo)=>{
    userinfo.value = userInfo
    saveUserInfoToStorage()
  }
  const saveUserInfoToStorage = ()=>{
    uni.setStorageSync('userinfo',JSON.stringify(userinfo.value))
  }
  // 更新收货地址
  const updateAddress = (address1)=>{
    address.value = address1
    saveToStorage()
  }
  // 本地持久化
  const saveToStorage = ()=>{
    uni.setStorageSync('address',JSON.stringify(address.value))
  }
  const updateToken = (Token)=>{
    token.value = Token
    saveTokenToStorage()
  }
  const saveTokenToStorage = ()=>{
    uni.setStorageSync('token',token.value)
  }
  // 重定向的对象（openType、from）
  const redirectInfo = ref(null)
  const updateRedirectInfo = (info)=>{
    redirectInfo.value = info
  }
  // computed
const addstr = computed(()=>{
  if(address.value.cityName === '') return ''
  
  return address.value.cityName + address.value.countyName + address.value.detailInfo
})
  return {
    address, 
    token,
    addstr,
    updateAddress,
    userinfo,
    updateUserInfo,
    updateToken,
    updateRedirectInfo,
    redirectInfo
    
   
  }
})